import java.util.Arrays;

public class heap {
//优先级队列概念
    //1.队列是一种先进先出的数据结构
    //2.PriorityQueue底层是堆, 数据结构是一个完全二叉树
//堆的概念
    //大根堆: 根节点大于左右孩子结点
    //小根堆: 根节点小于左右孩子结点
    //if i==0, i 表示的结点为根节点, 否则i结点的双亲结点为(i - 1)/2
    //if 2 * i + 1 < n, 则结点i的左孩子数下标为2 * i + 1, 否则没有左孩子
    //if 2 * i + 2 < n, 则结点i的右孩子数下标为2 * i + 2, 否则没有右孩子
    private int[] elem;
    private int usedSize;

    @Override
    public String toString() {
        return Arrays.toString(elem);
    }

    public heap() {
        this.elem = new int[10];
    }

    public void initElem(int[] array)
    {
        if(elem.length < array.length) Arrays.copyOf(this.elem, array.length);
        for(int i = 0; i < array.length; i++)
        {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap()
    {
        for(int parent = (this.usedSize - 1 - 1) / 2; parent >= 0; parent--)
        {
            siftDown(parent, usedSize);
        }
    }

    private void siftDown(int parent, int len) {
        int child = parent * 2 + 1;
        while(child < len)
        {
            if(child + 1 < len && this.elem[child] < elem[child + 1])
            {
                child = child + 1;
            }
            if(elem[child] > elem[parent])
            {
                swap(child, parent);
                parent = child;
                child = 2 * parent + 1;
            }
            else
            {
                break;
            }
        }
    }

    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void push(int val)
    {
        if(isFull()) elem = Arrays.copyOf(elem, 2 * elem.length);
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp(int child) {
        int parent = (child - 1) / 2;
        while (child > 0)
        {
            if(elem[child] > elem[parent])
            {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            }
            else
            {
                break;
            }
        }
    }

    public int pop()
    {
        if(isEmpty())
        {
            return -1;
        }
        int oldVal = elem[0];
        swap(0, usedSize - 1);
        usedSize--;
        siftDown(0, usedSize);
        return oldVal;
    }

    private boolean isEmpty() {
        return this.usedSize == 0;
    }

    private boolean isFull() {
        return this.usedSize == elem.length;
    }

    public static void main(String[] args) {
        heap testHeap = new heap();
        int[] array = {27,15,19,18,28,34,65,49,25,37};
        testHeap.initElem(array);

        testHeap.createHeap();

        System.out.println(testHeap.pop());
    }
}
